package org.cb.gui;

import java.awt.Color;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.File;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.GroupLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.cb.client.Client;
import org.cb.core.FontLoader;
import org.cb.core.FsigOCR;
import org.cb.core.Global;
import org.cb.core.ScriptBase;
import org.cb.types.Font;



/**
 * 
 * @author Unknown
 * 
 * Unknown = Fsig's computer.
 * Each file that starts with this
 * has been edited by me.
 * 
 * The Main GUI.
 *
 */
public class MainGUI extends JFrame implements ActionListener, ComponentListener{
	private static final long serialVersionUID = 4800424407531024669L;
	
	private JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
	private JPanel container = new JPanel();
	private JComponent rs_pane = Tab.makeTextPanel("New Pane");
	private static TextArea log; //Log
	
	static Date date;
	static SimpleDateFormat sdf=new SimpleDateFormat("dd/MMM/yyyy - HH:mm:ss");
	
	
	private JMenuBar menuBar = new JMenuBar();
	
	private JMenu mnFile = new JMenu("File");
	private JMenu mnEdit = new JMenu("Edit");
	private JMenu mnView = new JMenu("View");
	private JMenu mnTools = new JMenu("Tools");
	private JMenu mnScripts = new JMenu("Scripts");
	private JMenu mnRandoms = new JMenu("Randoms");
	private JMenu mnHelp = new JMenu("Help");
	
	private JMenuItem mntmExit = new JMenuItem("Exit");
	private JMenuItem mntmShowPaint = new JMenuItem("Show Paint");
	private JMenuItem mntmPaintMouse = new JMenuItem("Paint Mouse");
	private JMenuItem mntmBlockHuman = new JMenuItem("Block Human");
	private JMenuItem mntmPickColour = new JMenuItem("Pick Colour");
	private static JMenuItem mntmStartScript = new JMenuItem("Start Script");
	private JMenuItem mntmStartRandom = new JMenuItem("Start Random");
	private JMenuItem mntmAbout = new JMenuItem("About");
	
	private ImageIcon addImg = new ImageIcon(MainGUI.class.getResource("/Icons/add-icon.png"));
	private JButton addTab = new JButton(addImg);
	
	private static JFrame scriptLauncher;
	static Thread scriptThread;
	private static ScriptBase script;
	
	private FontLoader theFontLoader;
	private ArrayList<Font> theFonts;
	private ArrayList<Client> clients = new ArrayList<Client>();
	

	/**
	 * The main GUI
	 */
	public MainGUI() {
		this.setIconImage(Toolkit.getDefaultToolkit().getImage(MainGUI.class.getResource("/Icons/burn.png")));
		this.setTitle("Colour Bot V" + Global.getVersion() + " | Merchanting.net");
		this.setSize(786, 730);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setLayout(null);
		this.setJMenuBar(menuBar);
		this.addComponentListener(this);
		
		//Set icons
		mntmExit.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/button_cancel.png")));
		mntmPickColour.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/eyedropper.png")));
		mntmShowPaint.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
		mntmPaintMouse.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
		mntmBlockHuman.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
		mntmStartScript.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
		mntmStartRandom.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
		mntmAbout.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/help-book.png")));
		//Add items
		mnFile.add(mntmExit);
		mnEdit.add(mntmShowPaint);		
		mnEdit.add(mntmPaintMouse);
		mnEdit.add(mntmBlockHuman);
		mnTools.add(mntmPickColour);
		mnScripts.add(mntmStartScript);
		mnRandoms.add(mntmStartRandom);
		mnHelp.add(mntmAbout);
		//Add menus
		menuBar.add(mnFile);
		menuBar.add(mnEdit);
		menuBar.add(mnView);
		menuBar.add(mnTools);
		menuBar.add(mnScripts);
		menuBar.add(mnRandoms);
		menuBar.add(mnHelp);
		//Action listeners
		mntmExit.addActionListener(this);
		mntmShowPaint.addActionListener(this);
		mntmPaintMouse.addActionListener(this);
		mntmBlockHuman.addActionListener(this);
		mntmPickColour.addActionListener(this);
		mntmStartScript.addActionListener(this);
		mntmStartRandom.addActionListener(this);
		mntmAbout.addActionListener(this);

		//Add tabbed pane
		tabbedPane.setBounds(0, 0, 770, 678);
		
		//Add to the container
		GroupLayout containerLayout = new GroupLayout(container);
		container.setLayout(containerLayout);
		container.setBounds(0, 0, 776, 678);
		container.setBackground(Color.BLACK);
		
		rs_pane.setSize(776, 505);
		rs_pane.setBackground(Color.BLACK);
		container.add(rs_pane);
		
		log = new TextArea ("", 1, 1,  TextArea.SCROLLBARS_VERTICAL_ONLY);
		log.setBounds(0, 505, 768, 140);
		log.setEditable(false);
		container.add(log);
		
		//Add the tab*/
		tabbedPane.addTab("Bot 1", (Icon) null, container);
		tabbedPane.setTabComponentAt(0,new ButtonTabComponent(tabbedPane));

		
		addTab.setBounds(getWidth() - 40, 4, 16, 16);
		addTab.setBorder(null);
		addTab.addActionListener(this);
		this.add(addTab);
		this.add(tabbedPane);
		
		//Set visible before downloading
		this.setVisible(true);
		
		FsigOCR.loadLetters();
		downloadClient();
	}
	
	/**
	 * Download the client and add fonts
	 */
	private void downloadClient(){
		try {
			theFontLoader = new FontLoader();
			theFontLoader.loadFonts();
			theFonts = theFontLoader.getFonts();
			
			Client client = new Client(rs_pane, theFonts);
			clients.add(client);
		}catch (SocketTimeoutException e) {
			info("Couldn't connect to server, check your internet connection!");
		}catch (Exception e) {e.printStackTrace();}
	}

	/**
	 * Press a button
	 */
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == addTab){ //Add Tab
			info("Clicked add tab");
		}else if(e.getSource() == mntmExit){//Exit
			System.exit(0);
		}else if(e.getSource() == mntmShowPaint) {//Show Paint
			if(Global.isShouldPaint()){
				Global.setShouldPaint(false);
				mntmShowPaint.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
			}else{
				Global.setShouldPaint(true);
				mntmShowPaint.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
			}
			info("Painting = " + Global.isShouldPaint());
		}else if(e.getSource() == mntmPaintMouse){//Paint Mouse
			if(!Global.isPaintMouse()){
				Global.setPaintMouse(true);
				mntmPaintMouse.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
			}else{
				Global.setPaintMouse(false);
				mntmPaintMouse.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
			}
			info("Paint Mouse = " + Global.isPaintMouse());
		}else if(e.getSource() == mntmBlockHuman){//Block Human
			if(Global.isAllowMouse()){
				Global.setAllowMouse(false);
				mntmBlockHuman.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
			}else{
				Global.setAllowMouse(true);
				mntmBlockHuman.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
			}
			info("Block Human = " + Global.isAllowMouse());
		}else if(e.getSource() == mntmPickColour){//Pick colour at mouse
			if(!Global.isReadyToGetColour()){
				Global.setReadyToGetColour(true);
				mntmPickColour.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
			}else{
				Global.setReadyToGetColour(false);	
				mntmPickColour.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/eyedropper.png")));
			}
			
			info("Pick Colour = " + Global.isReadyToGetColour());
		}else if(e.getSource() == mntmStartScript){//Start / Stop Script
			if(!Global.isScriptRunning()){
				log("Loading script chooser.");
				scriptLauncher = new ScriptLauncher(new File(System.getProperty("user.dir") + "\\Scripts"));
			}else{
				log("Stopping script.");
				Global.setScriptRunning(false);
				
				if(scriptThread != null){
					scriptThread.interrupt();
				}

				Global.getTheCanvas().setScript(null);
				mntmStartScript.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
				mntmStartScript.setText("Start Script");
			}
		}else if(e.getSource() == mntmStartRandom){//Start Random
			
		}else if(e.getSource() == mntmAbout){//About the bot
			info("\nColour Bot was created by Stuart and Fsig.\nBase Rs loader based on wyn10's.");
		}
	}
	
	/**
	 * Method to start a script
	 * 
	 * @param className
	 */
	public static void startScript(final String className){
		info("\nClass name = " + className);
		scriptLauncher.setVisible(false);
		
		scriptThread = null;
		scriptThread = new Thread() {
			@Override
			public void run(){
				try {
					URLClassLoader scriptLoader = new URLClassLoader(new URL[] {new URL("file://" + new File("").getAbsolutePath() + "/Scripts/") });
					script = (ScriptBase) scriptLoader.loadClass(className).newInstance();
					Global.getTheCanvas().setScript(script);
					script.script();
				} catch (Exception e){
					log("Error: " + e.getMessage()); 
					log("Script Stopped.");
					Global.setScriptRunning(false);
					
					if(scriptThread != null){
						scriptThread.interrupt();
					}

					Global.getTheCanvas().setScript(null);
					mntmStartScript.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Play-icon.png")));
					mntmStartScript.setText("Start Script");
				}
			}
		};
		
		mntmStartScript.setIcon(new ImageIcon(MainGUI.class.getResource("/Icons/Stop-icon.png")));
		mntmStartScript.setText("Stop Script");
		
		scriptThread.start();
		Global.setScriptRunning(true);
	}
	
	/**
	 * Log the message with date and time stamp
	 * 
	 * @param msg
	 */
	public static void log(String msg){
		String[] count = log.getText().split("\n");
		
		if(count.length > 100){
			log.setText("");
		}
		
		date = new Date();
		String strDate = sdf.format(date);
		log.append("\n" + strDate + ": " + msg);
	}
	
	/**
	 * Log the info
	 * 
	 * @param msg
	 */
	public static void info(String msg){
		log.append(msg + "\n");
	}

	@Override
	public void componentResized(ComponentEvent e) {
		tabbedPane.setSize(getWidth() -16, getHeight() -61);
		rs_pane.setSize(rs_pane.getWidth(), getHeight() -230);
		rs_pane.setLocation((getWidth() /2) - (rs_pane.getWidth() /2) -5, 0);
		log.setSize(getWidth() -20, 145);
		log.setLocation(0, rs_pane.getHeight());
		addTab.setLocation(getWidth() - 40, 4);
	}
	
	@Override
	public void componentMoved(ComponentEvent e) {
		Global.setMainGUIx(this.getLocation().x);
		Global.setMainGUIy(this.getLocation().y);
		Global.setRs_panex(rs_pane.getLocation().x);
		Global.setRs_paney(rs_pane.getLocation().y);
	}
	
	public void componentHidden(ComponentEvent arg0) {}
	public void componentShown(ComponentEvent arg0) {}
}
